/**
 * Created by Administrator on 15-8-13.
 */
var Stage = RichBase.extend({
	EVENTS : {
		"mouseenter" : {
			".scrollBtn-left" : "scrollStageLeft",
			".scrollBtn-right" : "scrollStageRight"
		},
		"mouseleave" : {
			".scrollBtn-left" : "stopScrollStageLeft",
			".scrollBtn-right" : "stopScrollStageRight"
		},
		"click" : {
			".headBox" : "onHeadBoxClick",
			".headBox input" : "onHeadBoxInputClick",
			"#stageUl .stageBox" : "onStageBoxClick"
		},
		"blur" : {
			".headBox input" : "onChangeHeadBoxBlur"
		},
		"contextmenu" : {
			"#stageUl .stageBox" : "onStageContextMenu"
		},
		"mousedown" : {
			"#stageUl" : "onStageUlMouseDown_1"
		},
		"mousemove" : {
			"#stageUl" : "onStageUlMouseMove_1"
		},
		"mouseup" : {
			"#stageUl" : "onStageUlMouseUp_1"
		}
	},
	statics : {
		api : "call/jh_show.php",
		BOX_WIDTH : 38,
		SCROLL_LEFT_MOUSEENTER : false,
		SCROLL_RIGHT_MOUSEENTER : false,
		SCROLL_SPEED : 1000,
		AREA_COLORS : [
			"41bc95",
			"f37777",
			"edb734",
			"3cafd4",
			"e19acd",
			"5eb854",
			"9b8cdd",
			"4e95a1",
			"a7d57c",
			"f9d48f"
		],
		STATE : {
			"1" : {
				name : "预留",
				html : '<span class="sicon"><i class="iconfont" style="color:#cd3de2">&#xe68c;</i></span>'
			},
			"2" : {
				name : "锁定",
				html : '<span class="sicon"><i class="iconfont">&#xe62d;</i></span>'
			},
			"3" : {
				name : "已出售",
				html : '<span class="sicon saved"><i class="iconfont" style="color:#f7931e">&#xe68c;</i></span>'
			},
			"4" : {
				name : "", //已取消
				html : ""
			}
		}
	},
	orignData : {},
	isDrag : false,
	timer : null,
	mousedown_x : 0,
	init : function(opt){
		this.container = opt.container;
		this.stageUl = opt.stageUl;
		this.stageWidth = opt.stageWidth;
		this.offsetX = opt.offsetX;
		this.contextmenu = $("#contextMenuWrap");
		this.setVenueMenuLi = $("#setVenueMenuLi");
		this.roundId = $("#roundidHidInp").val();
		$("#contextMenuWrap").on("click",function(e){
			$(this).hide();
			return false;
		})
	},
	//页面onload时，pull该场馆数据，包括分区内的坐位数据，若存在坐位数据，则以此数据生成坐位分布图
	buildStage : function(){
		var that = this;
		var oData = this.orignData;
		var areas = oData.areas;
		var col_head = oData.col_head;
		var row_head = oData.row_head;
		col_head = col_head ? col_head.split(",") : [];
		row_head = row_head ? row_head.split(",") : [];
		this.create({
			row : oData.row_num,
			col : oData.col_num,
			layout : oData.layout
		});
		setTimeout(function(){
			for(var i in areas){
				var area = areas[i];
				var seats = area["seats"];
				var areaid = area["zone_id"];
				var areaColor = $("#areaList_li_"+areaid).attr("data-color");
				for(var s in seats){
					var dseat = seats[s];
					var seat_id = dseat["id"];
					var pyCol = dseat["col_num"];
					var row = dseat["row_num"];
					var tarBox = $("#stageBox_"+row+"_"+pyCol);
					var col = tarBox.attr("data-col");
					var seat = dseat["seat"];
					tarBox.attr("data-areaid",areaid).attr("data-seatid",seat_id).attr("data-seat",seat).css("background-color","#"+areaColor);
					if(seat!==row+"-"+col) tarBox.find(".t").text(seat);
				}
			}
			var colBoxs = $("#colHeadUl").children();
			for(var col=0; col<col_head.length; col++){
				var val = col_head[col];
				colBoxs.eq(col).text(val);
			}
			var rowBoxs_left = $("#stage-row-head-left .sUl").children();
			var rowBoxs_right = $("#stage-row-head-right .sUl").children();
			for(var row=0; row<row_head.length; row++){
				var val = row_head[row];
				rowBoxs_left.eq(row).text(val);
				rowBoxs_right.eq(row).text(val);
			}
			that.getRoundSeatState();
		},100)
	},
	//pull场馆里某一场次的座位状态数据
	getRoundSeatState : function(){
		var round_id = this.roundId;
		var STATE = this.statics.STATE;
		if(!round_id) return false;
		PFT.Ajax({
			url : "call/jh_round.php",
			type : "GET",
			dataType : "json",
			data : {
				action : "ROUND_SEAT_GET",
				round_id : round_id
			},
			loading : function(){},
			removeLoading : function(){},
			timeout : function(){},
			serverError : function(){}
		},function(res){
			var colls = res.collection;
			var stageUl = $("#stageUl");
			if(res.code==200 && colls){
				for(var i in colls){
					var coll = colls[i];
					var seatid = coll["seat_id"];
					var state = coll["status"];
					var tarBox = stageUl.children("[data-seatid="+seatid+"]").attr("data-state",state);
					tarBox.children(".state").html(STATE[state]["html"]);
					if(state==3) tarBox.addClass("isSaved");
				}
			}
		})
	},
	//push场馆里某一场次的座位状态数据
	submitRoundSeat : function(){
		var that = this;
		var round_id = this.roundId;
		var stageUl = $("#stageUl");
		var submitBtn = $("#saveBtn");
		var result = {};
		stageUl.children().each(function(){
			var box = $(this);
			var seatid = box.attr("data-seatid");
			var state = box.attr("data-state");
			if(seatid!="0" && state!="-1") result[seatid] = state;
		})
		PFT.Ajax({
			url : "call/jh_round.php?action=ROUND_SEAT_SET&round_id="+round_id,
			type : "POST",
			dataType : "json",
			data : result,
			loading : function(){ submitBtn.text("正在保存...").addClass("loading")},
			removeLoading : function(){submitBtn.text("保存").removeClass("loading")},
			timeout : function(){ alert("请求超时，请稍后重试")},
			serverError : function(){ alert("请求失败，请稍后重试")}
		},function(res){
			var code = res.code;
			var msg = res.msg || "保存出错，请稍后重试";
			if(code==200){
				PFT_GLOBAL.U.Alert("success",'<p style="width:160px">保存成功</p>',1000,function(){
					var venue_id = $("#venueIdHidInp").val();
					venue_id && (window.location.href="pft_show.html?m=rounds&rid="+venue_id)
				});
			}else if(code==0){
				alert("登录过期，请重新登陆");
			}else{
				alert(msg);
			}
		})
	},
	//push场馆数据至服务端
	submit : function(){
		if(this.roundId){
			this.submitRoundSeat();
			return false;
		}
		var that = this;
		var boxs = $("#stageUl").children();
		var data = this.orignData;
		var submitBtn = $("#saveBtn");
		data["row_num"] = $("#createSeatRowInp").val();
		data["col_num"] = $("#createSeatColInp").val();
		data["layout"] = $("#odd_first_optUl").find("input:radio:checked").hasClass("layoutType_1") ? 1 : 2;
		data["col_head"] = (function(){
			var arr = [];
			$("#colHeadUl").children().each(function(){
				var tarBox = $(this);
				var col = tarBox.text();
				arr.push(col);
			})
			return arr.join(",");
		})();
		data["row_head"] = (function(){
			var arr = [];
			$("#stage-row-head-left").children().children().each(function(){
				var tarBox = $(this);
				var row = tarBox.text();
				arr.push(row);
			})
			return arr.join(",");
		})();
		for(var i in data.areas){
			var area = data.areas[i];
			var zone_id = area["zone_id"];
			var seats = [];
			boxs.each(function(){
				var box = $(this);
				var id = box.attr("id");
				id = id.substring("stageBox_".length).split("_");
				var col = id[1];
				var row = id[0];
				var areaid = box.attr("data-areaid");
				if(zone_id == areaid){
//					seats.push({
//						row_num : box.attr("data-row"),
//						col_num : box.attr("data-col"),
//						seat : box.attr("data-seat"),
//						state : box.attr("data-state")
//					})
					seats.push({
						row_num : row,
						col_num : col,
						seat : box.attr("data-seat"),
						state : box.attr("data-state")
					})
				}
			})
			area["seats"] = seats;
		}
		PFT.Ajax({
			url : that.statics.api,
			type : "post",
			dataType : "json",
			data : {
				action : "set_seat",
				data : PFT_GLOBAL.U.JSON.stringify(that.orignData)
			},
			loading : function(){ submitBtn.text("正在保存...").addClass("loading")},
			removeLoading : function(){submitBtn.text("保存").removeClass("loading")},
			timeout : function(){ alert("请求超时，请稍后重试")},
			serverError : function(){ alert("请求失败，请稍后重试")}
		},function(res){
			if(res.status=="fail" && res.code==0){ //登录过期
				alert("登录过期，请重新登陆");
			}else if(res.status=="success"){
				PFT_GLOBAL.U.Alert("success",'<p style="width:120px">保存成功</p>',1000,function(){
					window.location.href="pft_show.html?m=venue_list";
				});
			}else{
				var msg = res.msg || "保存失败，请稍后重试";
				PFT_GLOBAL.U.Alert("fail",'<p style="width:200px">'+msg+'</p>');
			}
		})
	},
	scrollStageLeft : function(that,e){
		that.scrollStage(that,e,"left");
	},
	scrollStageRight : function(that,e){
		that.scrollStage(that,e,"right");
	},
	stopScrollStageLeft : function(that,e){
		that.onScrollMouseout(that,e);
	},
	stopScrollStageRight : function(that,e){
		that.onScrollMouseout(that,e);
	},
	scrollStage : function(that,e,dir){
		var tarBtn = $(e.currentTarget);
		var headUlW = $("#stage-col-head");
		var headUl = $("#colHeadUl");
		var stageUl = $("#stageUl");
		var distance = Math.abs(headUlW.width()-headUl.width());
		var left = headUl.css("left");
		if(headUl.is(":animated") || stageUl.is(":animated")) return false;
		if(left=="auto") left = "0px";
		left = Number(left.substring(0,left.length-2));
		left = Math.abs(left);
		var right = distance - left;
		var offsetLeft = tarBtn.hasClass("lt") ? 0 : (headUlW.width()-headUl.width());
		var _distance = (dir=="left") ? left : right;
		var SCROLL_SPEED = that.statics.SCROLL_SPEED * (Math.abs(_distance)/200);
		headUl.animate({left:offsetLeft},SCROLL_SPEED,"linear");
		stageUl.animate({left:offsetLeft},SCROLL_SPEED,"linear");
	},
	//右键
	onStageContextMenu : function(that,e){
		e.preventDefault ? e.preventDefault():(e.returnValue = false);
		var tarBox = $(e.currentTarget);
		if((that.roundId && tarBox.attr("data-seatid")=="0") || tarBox.hasClass("isSaved")) return false;
		var seat = tarBox.attr("data-seat");
		var contextmenu = that.contextmenu;
		var roundId = that.roundId;
		var cx = e.clientX;
		var cy = e.clientY;
		tarBox.addClass("selected");
		if(!tarBox.siblings(".selected").length){
			that.setVenueMenuLi.removeClass("unable").attr("data-seat",seat);
		}else{
			that.setVenueMenuLi.addClass("unable");
		}
		var seatArr = seat.split("-");
		if(!roundId){
			$("#menuGroupArea").show();
			$("#menuGroupDisable").show();
			$("#menuGroupSetseat").show();
			$("#menuGroupState").hide();
			$("#setSeat_row_input").val(seatArr[0]).attr("data-max",that.row);
			$("#setSeat_col_input").val(seatArr[1]).attr("data-max",that.col);
		}else{
			$("#menuGroupArea").hide();
			$("#menuGroupDisable").hide();
			$("#menuGroupSetseat").hide();
			$("#menuGroupState").show();
		}
		contextmenu.show().children(".contextMenuUl").css({left:cx,top:cy});
	},
	//左键单击
	onStageBoxClick : function(that,e){
		var tarBox = $(e.currentTarget);
		if(that.roundId && tarBox.attr("data-seatid")=="0") return false;
		if(tarBox.hasClass("isSaved")) return false;
		if(e.shiftKey){//如果按住shiftKey键
			if(tarBox.hasClass("selected")){
				tarBox.removeClass("selected");
			}else{
				var prev = tarBox.prevAll(".selected");
				if(prev.length){
					while(!tarBox.hasClass("selected")){
						tarBox.addClass("selected");
						tarBox = tarBox.prev();
					}
				}else{
					tarBox.addClass("selected");
				}
			}
		}else{
			tarBox.toggleClass("selected");
		}
	},
	onHeadBoxClick : function(that,e){
		if(that.roundId) return false;
		var tarBox = $(e.currentTarget);
		var tarNum = tarBox.text();
		var max = tarBox.hasClass("stage-col-head-box") ? that.col : that.row;
		tarBox.html('<input class="numInp" type="text" data-orign="'+tarNum+'" data-max="'+max+'" value="'+tarNum+'"/>');
		setTimeout(function(){
			tarBox.children().focus();
		},10)
	},
	onHeadBoxInputClick : function(that,e){
		e.stopPropagation();
	},
	//批量修改行号列号
	onChangeHeadBoxBlur : function(that,e){
		var tarInp = $(e.currentTarget);
		var tarBox = tarInp.parent();
		var index = tarBox.index();
		var oval = tarInp.attr("data-orign");
		var max = tarInp.attr("data-max");
		var val = tarInp.val();
		var colRow = tarBox.hasClass("stage-col-head-box") ? "col" : "row";
		var colRowVal = tarBox.attr("data-"+colRow);
		if(!val || !PFT_GLOBAL.U.isPositiveNum(val)){
			tarBox.text(oval);
		}else{
			tarBox.text(val);
			if(colRow=="row"){
				$("#stage-row-head-left .sUl").children().eq(tarBox.index()).text(val);
				$("#stage-row-head-right .sUl").children().eq(tarBox.index()).text(val);
			}
		}
		if(oval==val) return false;
		var tarColRows = $("#stageUl").children("[data-"+colRow+"="+colRowVal+"]");
		tarColRows.each(function(){
			var tarColRow = $(this);
			var seat = tarColRow.attr("data-seat");
			if(colRow=="col"){
				var row = seat.split("-")[0];
				tarColRow.attr("data-seat",row+"-"+val);
			}else{
				var row = seat.split("-")[1];
				tarColRow.attr("data-seat",val+"-"+row);
			}

		})
	},
	onScrollMouseout : function(that,e){
		var headUl = $("#colHeadUl");
		var stageUl = $("#stageUl");
		headUl.stop(true);
		stageUl.stop(true);
	},
	/**
	 * 生成坐位分布图
	 * @param opt
	 */
	create : function(opt){
		var opt = opt || {};
		if(!opt.row || !opt.col) return false;
		opt["col"] = Number(opt["col"]);
		opt["row"] = Number(opt["row"]);
		opt["layout"] = typeof opt["layout"]=="undefined" ? 1 : opt["layout"];
		var html = "";
		html += this.createColHead(opt);
		html += this.createStageBox(opt);
		opt["dir"] = "left";
		html += this.createRowHead(opt);
		opt["dir"] = "right";
		html += this.createRowHead(opt);
		this.container.html(html);
		setTimeout(function(){
			var stageUlW = $("#stageUlW");
			var stageUl = $("#stageUl");
			var colHeadUl = $("#colHeadUl");
			var scrollBtn = $("#stage-col-head").find(".scrollBtn");
			var distance = stageUlW.width()-stageUl.width();
			stageUl.css("left",distance/2);
			colHeadUl.css("left",distance/2);
			if(stageUlW.width()<stageUl.width()){
				scrollBtn.show();
			}else{
				scrollBtn.hide();
			}
		},10)
		this.row = opt.row;
		this.col = opt.col;
	},
	createStageBox : function(opt){
		var that = this;
		var col = opt.col;
		var row = opt.row;
		var layout = opt.layout;
		var colArr = this.getColArray(col,layout);
		var w = this.statics.BOX_WIDTH;
		var ulW = w*col+col;
		var html = "";
		html += '<div id="stageUlW" class="stageUlW"><ul id="stageUl" class="stageUl" style="width:'+ulW+'px">';
		for(var r=1; r<=row; r++){
			for(var c=0; c<colArr.length; c++){
//                console.log(r +'---' + (c+1))
				var data = {
					state : -1,
//					col : c+1,//Edit By Cgp@2015年8月9日13:43:20，使用矩阵的绝对行列坐标
					pyCol : c+1,
					col : colArr[c],
					row : r,
					width : w,
					height : w,
					area_id : -1,
					seat : r+"-"+colArr[c],
					seat_id : "0"
				};
				html += that.parseTemplate($("#stageBoxTpl").html(),data);
			}
		}
		html += '</ul></div>';
		return html;
	},
	createRowHead : function(opt){
		var row = opt.row;
		var dir = opt.dir || "left";
		var w = this.statics.BOX_WIDTH;
		var html = "";
		html += '<div id="stage-row-head-'+dir+'" class="stage-row-head '+dir+'"><ul class="sUl">';
		for(var r=1; r<=row; r++){
			html += '<li class="stage-row-head-box box headBox" data-row="'+r+'" style="width:'+w+'px; height:'+w+'px; line-height:'+w+'px">'+r+'</li>';
		}
		html += '</ul></div>';
		return html;
	},
	createColHead : function(opt){
		var col = opt.col;
		var layout = opt.layout;
		var colArr = this.getColArray(col,layout);
		var w = this.statics.BOX_WIDTH;
		var ulW = w*col+col;
		var html = "";
		html += '<div id="stage-col-head" class="stage-col-head"><div class="con"><ul id="colHeadUl" class="sUl" style="width:'+ulW+'px">';
		for(var i=0; i<colArr.length; i++){
			var c = colArr[i];
//            console.log(c);
			html += '<li class="stage-col-head-box box headBox" data-col="'+c+'" style="width:'+w+'px; height:'+w+'px; line-height:'+w+'px">'+c+'</li>';
		}
		html += '</ul></div>';
		html += '<span class="scrollBtn lt scrollBtn-left"><i class="iconfont">&#xe60c;</i></span>';
		html += '<span class="scrollBtn right scrollBtn-right"><i class="iconfont">&#xe60d;</i></span>';
		html += '</div></div>';
		return html;
	},
	getColArray : function(col,layout){
		var result = [];
		if(!col) return result;
		var layout = typeof layout=="undefined" ? 1 : layout;
		layout = Number(layout);
		col = Number(col);

//        for (var c=1;c<=col;c++) {
//            console.log(c);
//            result.push(c);
//        }
//        return result;

		if((col%2)>0){ //奇数
			if(layout==1){
				for(var c=col; c>=1; c-=2) result.push(c);
				for(var c=2; c<=col-1; c+=2) result.push(c);
			}else{
				for(var c=col-1; c>=2; c-=2) result.push(c);
				for(var c=1; c<=col; c+=2) result.push(c);
			}
		}else{ //偶数
			if(layout==1){
				for(var c=col-1; c>=1; c-=2) result.push(c);
				for(var c=2; c<=col; c+=2) result.push(c);
			}else{
				for(var c=col; c>=2; c-=2) result.push(c);
				for(var c=1; c<=col; c+=2) result.push(c);
			}
		}

		return result;
	},
	buildAreaList : function(areas){
		var t1 = "";
		var t2 = "";
		var states = this.statics.STATE;
		for(var i in areas){
			var area = areas[i];
			area["zone_color"] = area["zone_color"] || this.statics.AREA_COLORS[i];
			t1 += this.parseTemplate($("#areaListTpl").html(),area);
			t2 += this.parseTemplate($("#menuAreaListTpl").html(),area);
		}
		if(this.roundId){
			for(var i in states){
				var state = states[i];
				var name = state["name"];
				var html =  state["html"];
				t1 += '<li class="areaLi state">'+html+'<span class="t">'+name+'</span></li>'
			}
		}
		$("#areaHeadWrap").html(t1);
		$("#menuGroupArea").html(t2);
	},
	setOrignData : function(data){
		this.orignData = data;
	},
	onStageUlMouseDown : function(that,e){
		that.isDrag = true;
		that.mousedown_x = e.clientX;
	},
	onStageUlMouseMove : function(that,e){
		if(!that.isDrag){
			e.preventDefault();
			e.stopPropagation();
			return false;
		}
		var stageUl = $("#stageUl");
		var clientX = e.clientX;
		var offsetX = clientX - that.mousedown_x;
		var cLeft = stageUl.css("left");
		cLeft = cLeft=="0" ? "0px" : cLeft;
		cLeft = cLeft.substring(0,cLeft.length-2);
		cLeft = Number(cLeft);
		console.log("offsetX="+offsetX+" cLeft="+cLeft)
		stageUl.css({left:"+="+offsetX});
	},
	onStageUlMouseUp : function(that,e){
		that.isDrag = false;
	}
});